/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import controller.exceptions.NonexistentEntityException;
import controller.exceptions.PreexistingEntityException;
import controller.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import model.entity.Customer;
import model.entity.Caterer;
import model.entity.Favorite;

/**
 *
 * @author lnngu_000
 */
public class FavoriteJpaController implements Serializable {

    public FavoriteJpaController( EntityManagerFactory emf) {
        
        this.emf = emf;
    }
   
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Favorite favorite) throws PreexistingEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
           
            em = getEntityManager();
            em.getTransaction().begin();
            Customer customerId = favorite.getCustomerId();
            if (customerId != null) {
                customerId = em.getReference(customerId.getClass(), customerId.getCustomerId());
                favorite.setCustomerId(customerId);
            }
            Caterer catererId = favorite.getCatererId();
            if (catererId != null) {
                catererId = em.getReference(catererId.getClass(), catererId.getCatererId());
                favorite.setCatererId(catererId);
            }
            em.persist(favorite);
            if (customerId != null) {
                customerId.getFavoriteCollection().add(favorite);
                customerId = em.merge(customerId);
            }
            if (catererId != null) {
                catererId.getFavoriteCollection().add(favorite);
                catererId = em.merge(catererId);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findFavorite(favorite.getFavoriteId()) != null) {
                throw new PreexistingEntityException("Favorite " + favorite + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Favorite favorite) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            Favorite persistentFavorite = em.find(Favorite.class, favorite.getFavoriteId());
            Customer customerIdOld = persistentFavorite.getCustomerId();
            Customer customerIdNew = favorite.getCustomerId();
            Caterer catererIdOld = persistentFavorite.getCatererId();
            Caterer catererIdNew = favorite.getCatererId();
            if (customerIdNew != null) {
                customerIdNew = em.getReference(customerIdNew.getClass(), customerIdNew.getCustomerId());
                favorite.setCustomerId(customerIdNew);
            }
            if (catererIdNew != null) {
                catererIdNew = em.getReference(catererIdNew.getClass(), catererIdNew.getCatererId());
                favorite.setCatererId(catererIdNew);
            }
            favorite = em.merge(favorite);
            if (customerIdOld != null && !customerIdOld.equals(customerIdNew)) {
                customerIdOld.getFavoriteCollection().remove(favorite);
                customerIdOld = em.merge(customerIdOld);
            }
            if (customerIdNew != null && !customerIdNew.equals(customerIdOld)) {
                customerIdNew.getFavoriteCollection().add(favorite);
                customerIdNew = em.merge(customerIdNew);
            }
            if (catererIdOld != null && !catererIdOld.equals(catererIdNew)) {
                catererIdOld.getFavoriteCollection().remove(favorite);
                catererIdOld = em.merge(catererIdOld);
            }
            if (catererIdNew != null && !catererIdNew.equals(catererIdOld)) {
                catererIdNew.getFavoriteCollection().add(favorite);
                catererIdNew = em.merge(catererIdNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = favorite.getFavoriteId();
                if (findFavorite(id) == null) {
                    throw new NonexistentEntityException("The favorite with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            Favorite favorite;
            try {
                favorite = em.getReference(Favorite.class, id);
                favorite.getFavoriteId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The favorite with id " + id + " no longer exists.", enfe);
            }
            Customer customerId = favorite.getCustomerId();
            if (customerId != null) {
                customerId.getFavoriteCollection().remove(favorite);
                customerId = em.merge(customerId);
            }
            Caterer catererId = favorite.getCatererId();
            if (catererId != null) {
                catererId.getFavoriteCollection().remove(favorite);
                catererId = em.merge(catererId);
            }
            em.remove(favorite);
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Favorite> findFavoriteEntities() {
        return findFavoriteEntities(true, -1, -1);
    }

    public List<Favorite> findFavoriteEntities(int maxResults, int firstResult) {
        return findFavoriteEntities(false, maxResults, firstResult);
    }

    private List<Favorite> findFavoriteEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Favorite.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Favorite findFavorite(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Favorite.class, id);
        } finally {
            em.close();
        }
    }

    public int getFavoriteCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Favorite> rt = cq.from(Favorite.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
